const { userCollection } = require('../../common/constants')
const { ERROR } = require('../../common/error')
const { decryptData } = require('../../common/sensitive-aes-cipher')
const { dataDesensitization } = require('../../common/utils')

/**
 * 获取实名信息
 * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#get-realname-info
 * @param {Object} params
 * @param {Boolean} params.decryptData 是否解密数据
 * @returns
 */
module.exports = async function (params = {}) {
  // 添加调试日志，输出this.config的值
  console.log('DEBUG CONFIG:', JSON.stringify(this.config, null, 2));
  
  const schema = {
    decryptData: {
      required: false,
      type: 'boolean'
    }
  }

  this.middleware.validate(params, schema)

  const { decryptData: isDecryptData = true } = params

  const {
    uid
  } = this.authInfo
  const getUserRes = await userCollection.doc(uid).get()
  const userRecord = getUserRes && getUserRes.data && getUserRes.data[0]
  if (!userRecord) {
    throw {
      errCode: ERROR.ACCOUNT_NOT_EXISTS
    }
  }

  const { realname_auth: realNameAuth = {} } = userRecord

  // 添加更多调试信息
  console.log('REAL_NAME_AUTH:', JSON.stringify(realNameAuth, null, 2));
  console.log('REAL_NAME TYPE:', typeof realNameAuth.real_name);
  console.log('IDENTITY TYPE:', typeof realNameAuth.identity);
  console.log('REAL_NAME LENGTH:', realNameAuth.real_name ? realNameAuth.real_name.length : 0);
  console.log('IDENTITY LENGTH:', realNameAuth.identity ? realNameAuth.identity.length : 0);
  
  // 检查数据是否为有效的Base64
  const isBase64 = (str) => {
    if (typeof str !== 'string') return false;
    const base64Regex = /^[A-Za-z0-9+/]*={0,2}$/;
    return base64Regex.test(str) && str.length % 4 === 0;
  };
  
  console.log('REAL_NAME IS BASE64:', isBase64(realNameAuth.real_name));
  console.log('IDENTITY IS BASE64:', isBase64(realNameAuth.identity));
  
  let decryptedRealName, decryptedIdentity;
  
  if (isDecryptData) {
    try {
      console.log('Attempting to decrypt real_name...');
      if (!realNameAuth.real_name) {
        console.log('real_name is empty, skipping decryption');
        decryptedRealName = '';
      } else {
        decryptedRealName = decryptData.call(this, realNameAuth.real_name);
        console.log('Decrypted real_name success');
      }
    } catch (error) {
      console.error('Failed to decrypt real_name:', error);
      console.error('real_name value:', realNameAuth.real_name);
      throw error;
    }
    
    try {
      console.log('Attempting to decrypt identity...');
      if (!realNameAuth.identity) {
        console.log('identity is empty, skipping decryption');
        decryptedIdentity = '';
      } else {
        decryptedIdentity = decryptData.call(this, realNameAuth.identity);
        console.log('Decrypted identity success');
      }
    } catch (error) {
      console.error('Failed to decrypt identity:', error);
      console.error('identity value:', realNameAuth.identity);
      throw error;
    }
  }

  return {
    errCode: 0,
    type: realNameAuth.type,
    authStatus: realNameAuth.auth_status,
    realName: isDecryptData ? dataDesensitization(decryptedRealName, { onlyLast: true }) : realNameAuth.real_name,
    identity: isDecryptData ? dataDesensitization(decryptedIdentity) : realNameAuth.identity
  }
}
